package me.leiusual.sharing.repository.datasource

import androidx.paging.PageKeyedDataSource
import io.reactivex.observers.DisposableSingleObserver
import me.leiusual.sharing.api.ApiSharing
import me.leiusual.sharing.api.model.storesearch.StoreContent
import me.leiusual.sharing.api.model.storesearch.StoreSearch
import timber.log.Timber

/**
 * author: leiusual
 * create on: 2019-07-30
 * description:
 */
class StoreSearchDataSource(
    private val apiSharing: ApiSharing,
    private val keyword: String
) : PageKeyedDataSource<Int, StoreContent>() {

  override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, StoreContent>) {
    apiSharing.storeSearch(0, params.requestedLoadSize, keyword)
        .subscribe(object : DisposableSingleObserver<StoreSearch>() {

          override fun onError(e: Throwable) {
            Timber.w(e)
          }

          override fun onSuccess(t: StoreSearch) {
            callback.onResult(t.models.content, null, 1)
          }
        })
  }

  override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, StoreContent>) {
    // ignore
  }

  override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, StoreContent>) {
    apiSharing.storeSearch(params.key, params.requestedLoadSize, keyword)
        .subscribe(object : DisposableSingleObserver<StoreSearch>() {

          override fun onError(e: Throwable) {
            Timber.w(e)
          }

          override fun onSuccess(t: StoreSearch) {
            val list = t.models.content
            callback.onResult(list, if (list.size == params.requestedLoadSize) params.key + 1 else null)
          }
        })
  }
}